package cn.com.libertymutual.sys.nio;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.channels.SocketChannel;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class ReadFileData {

	private Logger log = LoggerFactory.getLogger(getClass());
	
	public String readFileName( SocketChannel socketChannel ) throws IOException {
    	ByteBuffer fileNameBuffer = ByteBuffer.allocate(3);
        socketChannel.read(fileNameBuffer);
        ///fileNameBuffer.flip();
        
        String fileNameLen = new String(fileNameBuffer.array(), 0, fileNameBuffer.limit());
        fileNameBuffer.clear();
        
        /*fileNameBuffer.put("done".getBytes());
        fileNameBuffer.flip();
        socketChannel.write(fileNameBuffer);
        fileNameBuffer.clear();*/
        int flen = Integer.parseInt(fileNameLen);
        fileNameBuffer = ByteBuffer.allocate( flen );
        StringBuilder fileBuf = new StringBuilder();
        
        int num;
        int offset = 0;
        while ((num = socketChannel.read(fileNameBuffer)) > 0) {  
        	fileNameBuffer.flip();
            // 写入文件  
            fileBuf.append( new String(fileNameBuffer.array(), 0, num) );
            
            fileNameBuffer.clear();
            
            offset += num;
            log.info("读取：{}", offset );
            if( offset < flen ) {
            	fileNameBuffer = ByteBuffer.allocate( flen - offset );
            }
            else {
            	log.info("文件名长度 {}，{}", flen, offset);
            	break;
            }
        }  
        
        return fileBuf.toString().trim();
    }
    
    @SuppressWarnings("resource")
	public FileChannel getFileChannel( SocketChannel socketChannel ) throws IOException {
    	FileChannel fileChannel = null;
    	
    	String filePathName = readFileName(socketChannel);
    	log.info(filePathName);
        File file = new File( filePathName );
        if( !file.getParentFile().exists() ) {
        	log.info("目录[{}]不存在，创建目录", file.getParent() );
        	file.getParentFile().mkdirs();
        }

        fileChannel = new FileOutputStream( file ).getChannel();
    	
    	return fileChannel;
    }
}
